﻿using adfsToShibMetadata.Mvc;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Xml.XPath;

namespace adfsToShibMetadata.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Index/
        public ActionResult Index()
        {
            // Prepare: Lots of boring stuff to get the xml file without certificate check
            HttpWebRequest request = HttpWebRequest.CreateHttp(ConfigurationManager.AppSettings["metadataUrl"]);
            request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            XDocument doc = XDocument.Load(receiveStream);

            // First, prepare the default namespace
            XNamespace defNamespace = doc.Root.GetDefaultNamespace();

            // Step 1: Add shibmd namespace to the document
            XNamespace shibmd = @"urn:mace:shibboleth:metadata:1.0";
            doc.Root.Add(new XAttribute(XNamespace.Xmlns + "shibmd", shibmd));

            // Step 2: Add scope to IDPSSO
            XElement Extensions = new XElement(defNamespace + "Extensions");
            XElement Scope = new XElement(shibmd + "Scope",
                new XAttribute("regexp", "false"),
                ConfigurationManager.AppSettings["shibScope"]
            );
            Extensions.Add(Scope);
            doc.Root.Element(defNamespace + "IDPSSODescriptor").AddFirst(Extensions);

            // Step 3: Delete the signature section
            XNamespace ds = @"http://www.w3.org/2000/09/xmldsig#";
            doc.Root.Element(ds + "Signature").Remove();

            // Additional Steps: Remove RoleDescriptor to make metadata smaller (not used by Shibboleth anyway)
            IEnumerable<XElement> roleDescriptors = doc.Root.Elements(defNamespace + "RoleDescriptor");
            foreach (XElement rd in roleDescriptors.ToList())
            {
                rd.Remove();
            }

            // That's all, now return the Xml to the caller
            return new XmlActionResult(doc);
        }

    }
}
